var gulp = require('gulp');
var fileinclude = require('gulp-file-include'); //HTML 拼接
var gulpSequence = require('gulp-sequence'); //任务串行
var clean = require('gulp-clean'); //清除文件
var rename = require('gulp-rename'); //文件改名
var minifyCss = require('gulp-minify-css'); //压缩CSS为一行；
var concat = require('gulp-concat'); //多个文件合并为一个；
var uglify = require('gulp-uglify'); //js代码压缩
var sass = require('gulp-sass'); //
var connect = require('gulp-connect'); // gulp server
// var map = require("map-stream");
// var sass = require ('gulp-sass'); // 读取用于编译Sass的插件

//清除dist文件
gulp.task('clean', function() {
  return gulp.src('./dist').pipe(clean());
});

//转移文件
gulp.task('copyFiles', function() {
  return gulp.src(['./src/img/**/*.*', './src/aa/**/*.*'], { base: 'src' }).pipe(gulp.dest('dist'));
});

//组合HTML文件
gulp.task('fileinclude', function() {
  return gulp
    .src('./src/pages/**/*.html')
    .pipe(
      fileinclude({
        prefix: '@@', //变量前缀 @@include
        basepath: './src/html', //引用文件路径
        indent: true //保留文件的缩进
      })
    )
    .pipe(gulp.dest('dist'));
});

//
gulp.task('Third-Party', function() {
  return gulp
    .src('./src/js/Third-Party/**/*.js')
    .pipe(concat('Third-Party.js'))
    .pipe(gulp.dest('./dist/js'));
});

//
gulp.task('scripts', function() {
  return gulp
    .src('./src/js/scripts/**/*.js')
    .pipe(concat('index.js'))
    .pipe(gulp.dest('./dist/js'));
});

//处理scss
gulp.task('sass', function() {
  return gulp
    .src(['./src/sass/index.scss'])
    .pipe(sass({ outputStyle: 'nested' }).on('error', sass.logError))
    .pipe(gulp.dest('dist/css'));
});

//监听 .scss 和 .js 文件
gulp.task('fileListener', function() {
  gulp.watch('./src/sass/**/*.scss', ['sass']);
  gulp.watch('./src/pages/**/*.html', ['fileinclude']);
  gulp.watch('./src/js/Third-Party/**/*.js', ['Third-Party']);
  gulp.watch('./src/js/scripts/**/*.js', ['scripts']);
});

//测试服务器
gulp.task('webserver', function() {
  connect.server({
    root: 'dist',
    livereload: false,
    port: 8081
  });
});

// gulp.task('default', gulpSequence('clean', 'fileinclude','sass'));
// gulp.task('default', gulpSequence('clean','scripts'));
gulp.task('default', gulpSequence('webserver', 'clean', 'copyFiles', 'sass', 'fileinclude', 'Third-Party', 'scripts', 'fileListener'));
